#!/bin/bash

#setup the firewall .ko and stuff, and check for sanity that all file exist, including .jar files ?
#run the logger as well?

# Usage: fwserver <binaries directory> <outgoing ip address for remoting>

# The default IP address for remoting
#SERVER_HOSTNAME="132.68.36.186"
SERVER_HOSTNAME="`ifconfig | grep 'inet addr' | awk '{print $2}' | cut -d':' -f2 | head -1`"

# Where are all the binaries located (not used yet !!!)
DEFAULT_PATH="/home/ubuntu/Desktop/ipcontext/binary"

if [ `whoami` != 'root' ]; then
	echo "Please run this program as root (type: sudo $0)"
	exit 1
fi
if [ -n "$1" ]; then
	pushd $1
	DEFAULT_PATH=$1
fi
if [ -n "$2" ]; then
	SERVER_HOSTNAME=$2
	echo "Starting server with address ${SERVER_HOSTNAME}."
else
	echo "Starting server with address ${SERVER_HOSTNAME}. If you want to change it, run fwserver with your hostname."
fi

#iptables -t nat -L > /dev/null
modprobe ip_conntrack
iptables -t mangle -L > /dev/null
if [ ! $? == "0" ]; then
	echo "An error has occoured while running iptables (Make sure your kernel is properly configured)."
	exit 1
fi
lsmod | awk '{print $1}' | grep ipt_ipcontext > /dev/null
if [ ! $? == "0" ]; then
	insmod ipt_ipcontext.ko > /dev/null
fi

#{ ps -el | grep daemon.py > /dev/null; } || python ./daemon.py
ps uax | grep "python" | grep "./daemon.py" > /dev/null
if [ ! $? == "0" ]; then
	python ./daemon.py 1>> $DEFAULT_PATH/log 2>> $DEFAULT_PATH/log &
fi

killall -9 rmiregistry > /dev/null
for pid in `ps uax | grep "java -cp server.jar" | grep server.Server | awk '{print $2}'`
do
	kill -9 $pid
done
sleep 1
CLASSPATH=".:server.jar" rmiregistry 1>> $DEFAULT_PATH/log 2>> $DEFAULT_PATH/log &
if [ `whoami` != 'root' ]; then
        echo "Please run this program as root (type: sudo $0)"
        exit
fi
java -cp server.jar:mysql-connector-java-5.0.4-bin.jar -Djava.security.policy=server.policy -Djava.rmi.server.hostname=${SERVER_HOSTNAME} -Djava.rmi.dgc.leaseValue=5000 server.Server 1>> $DEFAULT_PATH/log 2>> $DEFAULT_PATH/log &
if [ -n "$1" ]; then
	popd
fi
